#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    int fd[2] = { 0 };
    if(pipe(fd) < 0)
    {
        perror("pipe");
        return 1;
    }

    pid_t id = fork();
    if(id == 0) //子进程
    {
        //关闭读端0
        close(fd[0]);
        const char* msg = "chird message";
        int count = 5;
        while(count--)
        {
            write(fd[1],msg,strlen(msg));
            sleep(1);
        }
        close(fd[1]);
        exit(0);
    }
    //父进程，关闭写端
    close(fd[1]);
    char buff[64];
    while(1)
    {
        //读取数据
        ssize_t s = read(fd[0],buff,sizeof(buff));
        if(s > 0)
        {
            buff[s] = '\n';
            printf("Received information from the child process:%s\n",buff);
        }
        else if(s == 0)
        {
            printf("file end\n");
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
    close(fd[0]);
    //进程等待
    waitpid(id,NULL,0);
    return 0;
}